// Package app 需要注册的后台服务
package app

import (
	"cap/api"
	"cap/daemon/gua"
	"cap/dao"
	"context"
	"github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
)

type Daemon struct {
	exitFunc context.CancelFunc
}

func NewDaemon() *Daemon {
	return &Daemon{}
}

// Run runs the service and blocks until complete.
func (d *Daemon) Run(parentCtx context.Context) {
	var (
		g   errgroup.Group
		err error
	)
	ctx, cancelFunc := context.WithCancel(parentCtx)
	d.exitFunc = cancelFunc
	// 初始化数据库
	dao.InitDB()

	// 启动gua服务
	g.Go(func() error {
		defer func() {
			logrus.Errorf("tcp server exit，err:[%s]", err.Error())
		}()
		gua.NewManager()
		return err
	})

	// 启动http服务
	g.Go(func() error {
		defer func() {
			logrus.Errorf("http server exit,err:[%s]", err.Error())
		}()
		err = api.StartHttpServer(httpApiPrefix)
		return err
	})

	g.Go(func() error {
		defer func() {
			logrus.Debug("优雅关闭,协程-已退出")
			cancelFunc()
		}()
		<-ctx.Done()
		return nil //nolint
	})

	err = g.Wait()
	if err != nil {
		logrus.Debugf("shutting down the server: %v", err)
	}

}
